<template>
  <div class="container">
    <div class="flex flex-wrap f-ptp10">
      <CaseTypeSelect @getCaseType='getCaseType' class='f-mrt20 f-mbt10 f-w120' placeholder="案件类型"/>
      <el-input class='f-mrt20 f-mbt10 f-w120' v-model="caseId" clearable placeholder="案件编号"></el-input>
      <Region @getRegion='getRegion' placeholder="地区" class='f-mrt20 f-mbt10 f-w200' />
      <el-date-picker
        class='f-mrt20 f-mbt10 f-w120'
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期">
      </el-date-picker>
      <el-input class='f-mrt20 f-mbt10 f-w120' v-model="userId" clearable placeholder="用户id"></el-input>
      <el-input class='f-mrt20 f-mbt10 f-w120' v-model="userMobileNo" clearable placeholder="用户手机"></el-input>
      <el-select class='f-mrt20 f-mbt10 f-w120' v-model="state" clearable placeholder="状态">
        <el-option
          v-for="item in stateList"
          :key="item.value"
          :label="item.name"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button class='f-h40' @click="getList" type="primary">查询</el-button>
      <el-button class='f-h40' @click="dialogVisible = true" type="primary">新增招标</el-button>
    </div>
    <div>
      <el-table
        :data="biddingList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="案件编号" width="180"></el-table-column>
        <el-table-column prop="caseTypeName" label="案件类型" width="180"></el-table-column>
        <el-table-column label="地区" width="180">
          <template slot-scope="scope">
            <span>{{scope.row.provinceName}} {{scope.row.cityName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="用户ID" width="180"></el-table-column>
        <el-table-column prop="userMobileNo" label="用户手机" width="180"></el-table-column>
        <el-table-column prop="content" label="案件详情" width="120">
          <template slot-scope="scope">
            <span @click="showBtnClickEvent(scope.$index, scope.row)" class='s-c-green f-csp'>查看</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template slot-scope="scope">
            <span>{{ tranDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="manage" label="管理">
          <template slot-scope="scope">
            <span v-if="scope.row.state == 'tendering'" @click="biddingBtnClickEvent(scope.$index, scope.row)" class='s-c-green f-csp'>招标中</span>
            <span v-else-if="scope.row.state == 'solving'">进行中</span>
            <span v-else>已结束</span>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="totalCount > 0" class='f-ptp20 f-pbt20 f-oh'>
        <el-pagination
          class='f-fr'
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="totalCount">
        </el-pagination>
      </div>
    </div>

    <!-- dialog -->
    <el-dialog
      title="新增招标"
      :visible.sync="dialogVisible"
      @close='initAddInfo'
      width="800px">
      <div class='dialog-item f-oh'>
        <label class='f-fl' for="">用户ID</label>
        <div class='f-fl dialog-right'>
          <el-input @blur='blurEvent' class='f-w200' v-model="add_userId" placeholder="输入用户id"></el-input>
        </div>
      </div>
      <div class='dialog-item'>
        <label for="">用户手机</label>
        <div class='dialog-right'>
          <el-input class='f-w200' disabled v-model="add_userMobileNo" placeholder="输入用户id后回显"></el-input>
        </div>
      </div>
      <div class='dialog-item'>
        <label for="">案件标题</label>
        <div class='dialog-right'>
          <el-input class='f-w200' v-model="add_title" placeholder="标题"></el-input>
        </div>
      </div>
      <div class='dialog-item'>
        <label for="">案件地区</label>
        <div class='dialog-right'>
          <Region @getRegion='getAddRegion' ref='region' placeholder="请选择地区" class='f-w200' />
        </div>
      </div>
      <div class='dialog-item'>
        <label for="">案件类型</label>
        <div class='dialog-right'>
          <CaseTypeSelect ref='caseTypeSelect' @getCaseType='getAddCaseType' class='f-w200' placeholder="选择案件类型"/>
        </div>
      </div>
      <div class='dialog-item'>
        <label for="">案件详情</label>
        <div class='dialog-right full'>
          <quill-editor v-model="add_detail"
              placeholder='fsfsf'
              ref="myQuillEditor"
              :options="editorOption"
              @change="onEditorChange">
          </quill-editor>
          <input v-show='false' type="file" @change="upfile" id='upImg' ref="upImg" accept="image/png, image/jpeg, image/gif, image/jpg" />
        </div>
      </div>
      <div class='dialog-footer'>
        <el-button type="primary" @click="addBtnClickEvent">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="案件详情"
      :visible.sync="showDetial"
      center
      width="560px">
      <span v-html='currentCase && currentCase.content'></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showDetial = false">取 消</el-button>
        <el-button type="primary" @click="showDetial = false">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="招标中案件"
      :visible.sync="showBidding"
      center
      width="900px">
      <div>
        <div>
          <span class='f-mrt10'>案件类型：{{this.currentCase && this.currentCase.caseTypeName}}</span>
          <span class='f-mrt10'>案件地区：{{this.currentCase && this.currentCase.provinceName}} {{this.currentCase && this.currentCase.cityName}}</span>
          <span>用户手机：{{this.currentCase && this.currentCase.userMobileNo}}</span>
        </div>
        <div class='f-ptp10'>
          <el-table
            :data="applyList"
            border
            style="width: 100%">
            <el-table-column prop="lawyerId" label="投标律师" width="120"></el-table-column>
            <el-table-column prop="mobileNo" label="手机号" width="120"></el-table-column>
            <el-table-column label="律师所在地" width="120">
              <template slot-scope="scope">
                <span>{{scope.row.provinceName}} {{scope.row.cityName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="userId" label="擅长领域" >
              <template slot-scope="scope">
                <span>{{scope.row.skillFirstName}} {{scope.row.skillSecondName}} {{scope.row.skillSecondName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="投标时间" width="180">
              <template slot-scope="scope">
                <span>{{tranDate(scope.row.createTime)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template slot-scope="scope">
                <span @click="appointBtnClickEvent(scope.row)" class='s-c-green f-csp'>指派</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class='f-oh f-mtp10' v-if="applyTotalCount > 0">
          <el-pagination
            class='f-fr'
            @current-change="handleApplyCurrentChange"
            :current-page.sync="applyCurrentPage"
            :page-size="pageSize"
            background
            layout="total, prev, pager, next"
            :total="applyTotalCount">
          </el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showBidding = false">取 消</el-button>
        <!-- <el-button type="primary" @click="showBidding = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Region from '../components/Region'
import CaseTypeSelect from '../components/CaseTypeSelect'
import config from '../config'
export default {
  name: 'BiddingManage',
  components: {
    'Region': Region,
    'CaseTypeSelect': CaseTypeSelect
  },
  data() {
    return {
      editorOption: { 
        theme: 'snow',
        placeholder: '请在此输入咨询记录...',
        modules: {
          toolbar: {
            container: config.toolbarOptions,
            handlers: {
              'image': function(value) {
                if(value) {
                  document.querySelector('#upImg').click()
                } else {
                  this.quill.format('image', false);
                }
                
              }
            }
          }
        }
      }, // 富文本配置
      applyCurrentPage: 1, // 招标项目申请律师列表 当前页
      applyTotalCount: 0,  // 招标项目申请律师列表 总数量
      applyList: [],   // 招标项目申请律师列表
      currentCase: {}, // 当前选中的案件
      totalCount: 0,
      pageSize: 10,
      currentPage: 1,
      dialogVisible: false,
      showDetial: false,
      showBidding: false,
      biddingList: [],
      // add
      isUserId: false,
      add_userId: '',
      add_userMobileNo: '',
      add_detail: '',
      add_title: '',
      add_region: {},
      // search
      caseType: '',
      caseId: '',
      region: {},
      date: [],
      userId: '',
      userMobileNo : '',
      state: '',
      stateList: [
        {
          value: 'tendering',
          name: '招标中'
        },
        {
          value: 'solving',
          name: '进行中'
        },
        {
          value: 'done',
          name: '已结束'
        }
      ]
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // 上传
    upfile(e) {
      const files = e.target.files;
      const form = new FormData();
      form.append("file", files[0]);
      form.append("dir", "notice");
      form.append("type", "1");
      this.$store.dispatch("UPLOAD_FILE", form).then(res => {
        if (res.data.retCode == 0) {
          this.$message.success("上传成功！");
          // 获取富文本组件实例
            let quill = this.$refs.myQuillEditor.quill;
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data.data)
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      });
    },
    onEditorChange({ quill, html, text }) {
      console.log('editor change!-quill', quill, html, text)
      console.log('editor change!-html', html)
      console.log('editor change!-text', text)
      this.add_detail = html;
    },
    // 指派按钮点击事件
    appointBtnClickEvent(row) {
      this.$confirm('确定指律师id为' + row.lawyerId + '的律师为该案件服务！', '提示').then(() => {
        this.appointLawyer(row);
      }) 
    },
    // 指派律师
    appointLawyer(data) {
      this.$store.dispatch('ASSIGN_LAWYER', {
        caseId: data.caseId,
        lawyerId: data.lawyerId
      }).then(res => {
        if(res.data.retCode == 0) {
          this.$message.success('指派成功！');
          this.getList();
          this.showBidding = false;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      })
    },
    handleApplyCurrentChange(page) {
      this.applyCurrentPage = page;
      this.getApplyList();
    },
    // 根据caseId 获取案件招标申请律师列表
    getApplyList(caseId) {
      this.$store.dispatch('BIDDING_APPLY_BY_LAWYER_LIST', {
        caseId,
        pageNum: this.applyCurrentPage - 1,
        pageSize: this.pageSize
      }).then(res => {
        console.log('res:::', res);
        if(res.data.retCode == 0) {
          this.applyList = res.data.data;
          this.applyTotalCount = res.data.totalCount;
        }
      }).catch(err => {
        console.error('获取招标项目申请律师列表：：', err)
      })
    },
    tranDate(date) {
      return this._utils.format(date, 'yyyy-mm-dd');
    },
    initAddInfo() {
      this.add_userMobileNo = '';
      this.isUserId = false;
      this.add_detail = '';
      this.add_title = '';
      this.add_userId = '';
      this.add_caseType = '';
      this.add_region = {};
      this.$refs.region.clear();
      this.$refs.caseTypeSelect.clear();
    },
    addBtnClickEvent() { // 新增招标-确定按钮点击事件
      if(!this.isUserId) {
        this.$message.warning('请输入正确的id');
        return;
      }
      if(this._utils.isEmpty(this.add_title)) {
        this.$message.warning('请输入案件标题!');
        return;
      }
      if(!(this.add_region.province && this.add_region.city)) {
        this.$message.warning('请选择案件地区!');
        return;
      }
      if(this._utils.isEmpty(this.add_caseType)) {
        this.$message.warning('请选择案件类型!');
        return;
      }
      if(this._utils.isEmpty(this.add_detail)) {
        this.$message.warning('请输入案件详情!');
        return;
      }
      this.addBidding();
    },
    addBidding() {
      this.$store.dispatch('ADD_BIDDING', {
        userId: this.add_userId,
        province: this.add_region.province.id,
        city: this.add_region.city.id,
        caseType: this.add_caseType, 
        title: this.add_title,
        content: this.add_detail
      }).then(res => {
        console.log('新增招标：：', res);
        if(res.data.retCode == 0) {
          this.$message.success('新增成功！');
          this.dialogVisible = false;
          this.currentPage = 1;
          this.getList();
        }
      }).catch(err => {
        console.error('新增招标：：', err)
      })
    },
    blurEvent() { // 新增-用户id输入框失去焦点事件
      console.log('this.add_userId:::', this.add_userId);
      if(/^\d+$/.test(this.add_userId)) {
        this.getUserById(this.add_userId);
      } else {
        this.$message.warning('请输入正确id格式，id为纯数字');
      }
    },
    getUserById(userId) { // 根据用户id查询用户信息
      this.$store.dispatch('QUERY_USER', {
        id: userId
      }).then(res => {
        console.log('res::', res);
        if(res.data.retCode == 0) {
          if(res.data.data) {
            this.add_userMobileNo = res.data.data.mobileNo;
            this.isUserId = true;
          } else {
            this.$message.warning('用户id不存在');
            this.add_userMobileNo = '';
            this.isUserId = false;
          }
        }
      })
    },
    getCaseType(caseType) { // 获取搜索条件， 案件类型
      this.caseType = caseType;
    },
    getAddCaseType(caseType) { // 新增-获取案件类型
      this.add_caseType = caseType;
    },
    getRegion(obj) {  // 搜索-获取地区
      console.log('arr:::', obj);
      this.region = obj;
    },
    getAddRegion(obj) { // 新增招标-获取地区
      this.add_region = obj;
    },
    getList() {
      console.log('this.caseType::', this.caseType);
      const params = {
        pageNum: this.currentPage - 1,
        pageSize: this.pageSize,
        caseType: this.caseType,
        caseId: this.caseId,
        province: this.region.province && this.region.province.id,
        city: this.region.city && this.region.city.id,
        startDay: this._utils.getType(this.date) == 'Array' && this.date.length > 0 ? this._utils.format(this.date[0], 'yyyy-mm-dd') : '',
        endDay: this._utils.getType(this.date) == 'Array' && this.date.length > 0 ? this._utils.format(this.date[1], 'yyyy-mm-dd') : '',
        userId: this.userId,
        userMobileNo : this.userMobileNo,
        caseState: this.state
      }
      this.$store.dispatch('GET_BIDDING_LIST', params).then(res => {
        console.log('res:::', res);
        if(res.data.retCode == 0) {
          this.biddingList = res.data.data;
          this.totalCount = res.data.totalCount;
        } else {
          res.data.errorMsg && this.$message.warning(res.data.errorMsg);
        }
      }).catch(err => {
        console.error('获取招标列表：：', err)
      })
    },
    showBtnClickEvent(index, row) { // 查看按钮点击事件
      this.showDetial = true;
      this.currentCase = row;
    },
    biddingBtnClickEvent(index, row) {  // 招标中 按钮点击事件
      this.showBidding = true;
      this.currentCase = row;
      this.getApplyList(row.caseId);
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getList();
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.dialog-item{
  overflow: hidden;
  padding-bottom: 10px;
}
.dialog-item>label{
  width: 65px;
  line-height: 40px;
  text-align: right;
  float: left;
}
.dialog-item .dialog-right{
  padding: 0 20px;
  float: left;
}
.dialog-footer{
  padding-left: 85px;
  padding-top: 20px;
}
.full{
  width: 650px;
}
</style>
